import { Component, ViewEncapsulation } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { deepClone, getValueUsingField, replaceAll } from '../../../utils/utils';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { DrawerInquiryComponent } from '@shared/drawer-inquiry';
import { DrawerVehicleMasterControlComponent } from '@shared/drawer-vehicleMasterControl';
import { ApesDrawerCustomGridComponent } from '@shared/ag-grid-ext/drawer-custom/drawer-custom-grid.component';
import { ApesDrawerService } from '@shared/apes/drawer';

@Component({
  selector: 'apes-render-multipleLines',
  template: `
    <ng-container *ngFor="let item of items">
      <div class="apes-render-multipleLines">
        <div *ngIf="item.name">{{item.name}}&nbsp;:&nbsp;</div>
        <div [ngClass]="{action:item.action}" (click)="clickOperating(item)">{{getMultipleLinesFormatter(item)}}</div>
      </div>
    </ng-container>
  `,
  styles: [
      `
      .apes-render-multipleLines {
        display: flex;
        justify-content: flex-start;
        line-height: 1.5;
      }

      .apes-render-multipleLines .action {
        color: #03a9f4;
        cursor: pointer;
      }
    `,
  ],
})
export class RenderMultipleLinesComponent implements ICellRendererAngularComp {
  params: any;
  items: any = null;

  ctx: any = {};
  data: any = {};
  apesConfig: any;

  constructor(
    private expressionService: ExpressionService,
    private contextService: ApesContextMenuService,
    protected drawerService: ApesDrawerService,
  ) {
  }

  refresh(params: any): boolean {
    return false;
  }

  agInit(params): void {
    this.params = params;
    this.ctx = params.context;

    if (params.context) {
      this.ctx = params.context;
    }

    this.apesConfig = this.extend(params);
    this.apesConfig = { ...this.apesConfig, ...params['column']['colDef'] };

    if (this.params.hasOwnProperty('colDef')) {
      this.data = this.params.data;
      this.items = this.replaceItems(this.params.colDef.items);
    } else {
      this.data = this.params.node.data;
      this.items = this.replaceItems(this.params['column']['colDef'].items);
    }
  }

  clickOperating(btn) {
    if (!btn.hasOwnProperty('action')) return;
    if (btn.action == 'link') {
      this.openLink(btn);
    } else if (btn.action == 'drawer') {
      this.openDrawer(btn);
    }
  }

  extend(data: any) {
    let result = {};
    for (let key in data) {
      let value = data[key];
      if (key === 'context') {
        result['ctx'] = value;
      } else {
        result[key] = value;
      }
    }
    return result;
  }

  // 链接
  openLink(params) {
    let data = this.data;
    let config = deepClone(params.config);
    let callbackBody = this.apesConfig.callback;

    let api = this.expressionService.evaluate(params.api, {
      context: this.ctx,
      model: this.ctx['model'],
      data: this.data,
    });

    let configApi = this.expressionService.evaluate(config.api, {
      context: this.ctx,
      model: this.ctx['model'],
      data: this.data,
    });

    if (api == null) {
      api = params.api;
    }

    if (configApi != null) {
      config.api = configApi;
    }

    let resultData = {};
    if (callbackBody) {
      let node = { ...params };
      resultData = this.expressionService.evaluate(callbackBody, {
        context: this.ctx,
        model: this.ctx['model'],
        data: this.data,
        node: node,
      }, true);
    } else {
      resultData = data;
    }

    if (data.hasOwnProperty('FORM_ID')) {
      api = data['FORM_ID'];
      config.api = data['API'];
    }
    this.contextService.openContextLink(resultData, api, config);
  }

  // 抽屉
  openDrawer(params) {
    let formId = '';
    let title = '';
    let width = '38vw';
    let drawer;

    if (params.hasOwnProperty('formId')) {
      formId = this.expressionService.evaluate(params.formId, {
        context: this.ctx,
        model: this.ctx['model'],
        data: this.data,
      });
      if (formId == null) formId = params.formId;

    } else {
      formId = this.expressionService.evaluate(params.api, {
        context: this.ctx,
        model: this.ctx['model'],
        data: this.data,
      });
      if (formId == null) formId = params.api;
    }

    if (params.hasOwnProperty('title')) {
      title = params.title;
    } else {
      title = params.name;
    }
    if (params.hasOwnProperty('width')) {
      width = params.width;
    }
    if (params.hasOwnProperty('link')) {
      this.ctx['link'] = params.link;
    }
    const data = {
      ...this.ctx.model, node: this.params.node['data'], link: this.ctx['link'],
      // conditionModel: { ...this.ctx.model, node: this.params.node['data'] },
    };
    if (params.hasOwnProperty('custom')) {
      if (params.custom == 'PlatformInquiry') {
        drawer = DrawerInquiryComponent;
      } else if (params.custom == 'VehicleMasterControl') {
        drawer = DrawerVehicleMasterControlComponent;
      }
    }

    const openDrawer = drawer ? drawer : ApesDrawerCustomGridComponent;

    const drawerRef = this.drawerService.create<DrawerVehicleMasterControlComponent, { formId: string, api: string, data: any }, string>({
      apesTitle: title,
      apesContent: openDrawer,
      apesWidth: width,
      apesContentParams: {
        formId: formId,
        api: params.api,
        data: data,
      },
    });
    drawerRef.afterOpen.subscribe(() => {
    });

    drawerRef.afterClose.subscribe(data => {
    });
  }


  replaceItems(items) {
    let list;
    list = replaceAll(items, '\'', '"');
    list = replaceAll(list, '`', '\'');
    list = JSON.parse(list);
    return list;
  }

  getMultipleLinesFormatter(item): string {
    let showText = '';
    let expression = item.value;
    showText = this.expressionService.evaluate(expression, {
      context: this.ctx,
      model: this.ctx['model'],
      data: this.data,
    });
    return showText;
  }

}
